import React, { useState } from "react";
import { Popover, Input, Tag, Button, message } from "antd";
import popverStyle from "./blpopver.module.scss";
export default function Blpopver(props) {
  const [open, setOpen] = useState(false);
  const { list, type, onChange, setField } = props;
  console.log(list,"list")
  return (
    <>
      <Popover
        content={
          <Content
            list={list}
            type={type}
            onChange={onChange}
            onClose={setOpen}
            setField={setField}
          />
        }
        open={open}
        title={type === 1 ? "分类" : "标签"}
        trigger="click"
        placement="bottom"
      >
        <Button
          className={type === 1 ? popverStyle.cateBtn : popverStyle.tagBtn}
          onClick={() => setOpen(true)}
        >
          {type === 1 ? "添加分类" : "添加标签"}
        </Button>
      </Popover>
    </>
  );
}

function Content(props) {
  console.log(props, "contentporps");
  const { list, type, onChange, onClose, setField } = props;
  const handleChange = (e) => {
    // 通过getAttribute获取到id
    const id = parseInt(e.target.getAttribute("name"));
    const name = e.target.innerText;
    console.log(typeof id, "idd");

    if (type === 1) {
      onChange({ id, typeName: name });
    setField({ id, typeName: name });

    } else {
      onChange((pre) => {
        console.log(pre, "prestate");
        if(!pre) {
          setField([{ id, tagName: name }])
          return [{ id, tagName: name }];
        }
        if (pre.length > 0 && pre.find((item) => item.id === id)) {
          message.info("请不要选择重复的标签！");
          return pre;
        }
        setField([...pre, { id, tagName: name }])
        return [...pre, { id, tagName: name }];
      });
      
    }
    onClose(false);
  };
  return (
    <>
      <Input
        placeholder={
          type === 1
            ? "请输入分类名,按enter添加自定义分类"
            : "请输入标签名,按enter添加自定义标签"
        }
      ></Input>
      <div className="title">选择以下{type === 1 ? "分类" : "标签"}：</div>
      <div className="tags" onClick={handleChange}>
        {type === 1
          ? list.map((item) => {
              return (
                <Tag color="skyblue" key={item.id} name={item.id}>
                  {item.typeName}
                </Tag>
              );
            })
          : list.map((item) => {
              return (
                <Tag color="skyblue" key={item.id} name={item.id}>
                  {item.tagName}
                </Tag>
              );
            })}
      </div>
    </>
  );
}
